﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using WindowsPhoneApplication1.Connectors;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;

namespace WindowsPhoneApplication1
{
    public partial class AfterLoginPivotPage : PhoneApplicationPage
    {
        bool isInit = false;
        string photo = null;


        public AfterLoginPivotPage()
        {
            InitializeComponent();
            isInit = true;

            subscriptionsLP.Items.Add(new WebServiceDataSources.Subscription() { tracked_user_path = "--" });

            UpdatesConnector.Alpp = this;
        }

        private void BliposphereListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BliposphereListBox.SelectedItem != null)
            {
                string statusId = ((WebServiceDataSources.Status)BliposphereListBox.SelectedItem).id.ToString();
                NavigationService.Navigate(new Uri("/Views/SingleStatusPage.xaml?SID=" + statusId, UriKind.Relative));
                BliposphereListBox.SelectedItem = null;
            }
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (isInit)
            {
                if (NavigationService.CanGoBack)
                    NavigationService.RemoveBackEntry();

                ApplicationBar = new ApplicationBar();

                ApplicationBar.IsVisible = true;
                ApplicationBar.Mode = ApplicationBarMode.Minimized;
                ApplicationBar.Opacity = 0.8;

                ApplicationBarMenuItem refresh = new ApplicationBarMenuItem("odśwież");
                refresh.Click += new EventHandler(refresh_Click);
                ApplicationBar.MenuItems.Add(refresh);

                ApplicationBarMenuItem logout = new ApplicationBarMenuItem("wyloguj");
                logout.Click += new EventHandler(logout_Click);
                ApplicationBar.MenuItems.Add(logout);

                UpdatesConnector.GetUserUpdates();

                UpdatesConnector.GetBliposphere();
                PicturesConnector.GetNewestPictures();
                SubscriptionsConnector.GetSubscriptionsFrom();

                isInit = false;
            }
        }

        void logout_Click(object sender, EventArgs e)
        {
            AppSettings.Instance.Username = AppSettings.Instance.Password = "";
            NavigationService.Navigate(new Uri("/Views/StartNoLoginPanorama.xaml", UriKind.Relative));
        }

        void refresh_Click(object sender, EventArgs e)
        {
            UpdatesConnector.GetUserUpdates();

            UpdatesConnector.GetBliposphere();
            PicturesConnector.GetNewestPictures();
            SubscriptionsConnector.GetSubscriptionsFrom();
        }

        public void UpdateUpdatesDataSource(List<WebServiceDataSources.Status> statuses)
        {
            Dispatcher.BeginInvoke(() =>
            {
                BliposphereListBox.DataContext = statuses;
            });
        }

        public void UpdateSubsriptionsList(List<WebServiceDataSources.Subscription> subscriptions)
        {
            Dispatcher.BeginInvoke(() =>
            {
                subscriptions.Insert(0, new WebServiceDataSources.Subscription() { tracked_user_path = "--" });
                subscriptionsLP.DataContext = subscriptions;
                //subscriptionsLP.Items.Insert(0, new WebServiceDataSources.Subscription() { tracked_user_path = "--" });
            });
        }

        public void UpdateBliposphereDataSource(List<WebServiceDataSources.Status> statuses)
        {
            Dispatcher.BeginInvoke(() =>
            {
                BliposphereListBox1.DataContext = statuses;
            });
        }

        public void UpdateNewestPhotos(List<WebServiceDataSources.Picture> pictures)
        {
            Dispatcher.BeginInvoke(() =>
            {
                PicturesListBox.DataContext = pictures;
            });
        }

        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string updatePath = ((Image)sender).Tag.ToString();
            string statusId = updatePath.Split('/').Last();
            NavigationService.Navigate(new Uri("/Views/SingleStatusPage.xaml?SID=" + statusId, UriKind.Relative));
        }

        private void BliposphereListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BliposphereListBox1.SelectedItem != null)
            {
                string statusId = ((WebServiceDataSources.Status)BliposphereListBox1.SelectedItem).id.ToString();
                NavigationService.Navigate(new Uri("/Views/SingleStatusPage.xaml?SID=" + statusId, UriKind.Relative));
                BliposphereListBox1.SelectedItem = null;
            }
        }

        private void postMsg_KeyUp(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (e.Key == Key.Enter && tb != null)
            {
                string s = tb.Text;
                if (s.Length > 0)
                    UpdatesConnector.PostUpdate(tb.Text, photo);
            }
        }

        private void ListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListPicker lp = sender as ListPicker;

            if (lp != null && GoToTextBox != null)
            {
                if (lp.SelectedIndex == 0)
                {
                    if (GoToTextBox.Text.Length > 0 && GoToTextBox.Text[0] == '#')
                        GoToTextBox.Text = '>' + GoToTextBox.Text.Substring(1);
                    else if (GoToTextBox.Text.Length > 0 && GoToTextBox.Text[0] != '>')
                        GoToTextBox.Text = GoToTextBox.Text.Insert(0, ">");
                    else if (GoToTextBox.Text.Length == 0)
                        GoToTextBox.Text = GoToTextBox.Text.Insert(0, ">");
                }
                else if (lp.SelectedIndex == 1)
                {
                    if (GoToTextBox.Text.Length > 0 && GoToTextBox.Text[0] == '>')
                        GoToTextBox.Text = '#' + GoToTextBox.Text.Substring(1);
                    else if (GoToTextBox.Text.Length > 0 && GoToTextBox.Text[0] != '#')
                        GoToTextBox.Text = GoToTextBox.Text.Insert(0, "#");
                    else if (GoToTextBox.Text.Length == 0)
                        GoToTextBox.Text = GoToTextBox.Text.Insert(0, "#");
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string s = postMsg.Text;
            if (s.Length > 0)
                UpdatesConnector.PostUpdate(postMsg.Text, photo);
        }

        private void subscriptionsLP_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListPicker lpi = sender as ListPicker;
            WebServiceDataSources.Subscription s = lpi.SelectedItem as WebServiceDataSources.Subscription;
            if (s != null)
            {
                var splitted = s.tracked_user_path.Split('/');
                string username = splitted[splitted.Length - 1];

                if (username != "--")
                {
                    if (postMsg.Text.Length > 0 && postMsg.Text[0] == '>')
                    {
                        if (postMsg.Text.Length > 1 && postMsg.Text[1] == '>')
                        {
                            if (postMsg.Text.Length > 2 && !char.IsWhiteSpace(postMsg.Text[2]))
                                postMsg.Text = postMsg.Text.Remove(0, postMsg.Text.IndexOf(' '));
                        }
                        else if (postMsg.Text.Length > 1 && !char.IsWhiteSpace(postMsg.Text[1]))
                            postMsg.Text = postMsg.Text.Remove(0, postMsg.Text.IndexOf(' '));
                            
                    }
                        postMsg.Text = postMsg.Text.Insert(0, prvMsg.IsChecked.Value ? ">>" : ">" + username + ": ");
                }
            }
        }

        private void jumpToButton_Click(object sender, RoutedEventArgs e)
        {
            if (GoToTextBox.Text.Length > 2)
            {
                if (typeSearch.SelectedIndex == 0)
                {
                    NavigationService.Navigate(new Uri("/Views/SingleUserPage.xaml?UID=" + (GoToTextBox.Text[0] == '>' ? GoToTextBox.Text.Substring(1) : GoToTextBox.Text), UriKind.Relative));
                }
                else
                {

                }
            }
        }

        private void GoToTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                jumpToButton_Click(null, null);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask photoChooserTask;
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);

            try
            {
                photoChooserTask.Show();
            }
            catch (System.InvalidOperationException ex)
            {
                MessageBox.Show("Nie można dodać zdjęcia.");
            }
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                choosePhotoButton.Content = "zmień fotkę";

                //Code to display the photo on the page in an image control named myImage.
                System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
                bmp.SetSource(e.ChosenPhoto);
                //myImage.Source = bmp;

                WriteableBitmap wb = new WriteableBitmap(bmp);
                    //Dispatcher.BeginInvoke(() =>
                    //    {
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.SaveJpeg(ms, bmp.PixelWidth, bmp.PixelHeight, 0, 80);

                    string photoConverted = Convert.ToString(ms.GetBuffer());

                    photo = photoConverted;
                }
            }
        }
    }
}
